package com.dronff.handler;

import com.dronff.protocol.TangProtocol;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.charset.StandardCharsets;

public class TangProtocolInvokerOutboundHandler extends MessageToByteEncoder<TangProtocol> {

    static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 协议格式
     * |1 byte  |  4 byte|
     * |   0    | 包总长度|
     * @param channelHandlerContext
     * @param tangProtocol
     * @param byteBuf
     * @throws Exception
     */
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, TangProtocol tangProtocol, ByteBuf byteBuf) throws Exception {
        // 标志字节
        byteBuf.writeChar(0);
        byte[] bytes = objectMapper.writeValueAsBytes(tangProtocol);
        byteBuf.writeInt(bytes.length);
        byteBuf.writeBytes(bytes);
    }
}
